﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Infragistics.Controls.Schedules;
using Infragistics.Controls.Interactions;
using Infragistics.Controls.Schedules.Primitives;
using Ivvy_Silverlight.i7SR;

namespace Ivvy_Silverlight.Ivvy
{
    public partial class Customized_Appointment_Dialog : UserControl
    {
        public DataManipulations CurrentDataManager = null;
        public static int NewCalendarItemID = -1111111;
        public i_CalendarItem NewCalendarItem = null;
        public ObservableCollection<i_vw_Appointment_Detail> Currentvw_Appointment_DetailList = null;
        public ExtendedAppoIntMent CurrentActivity = new ExtendedAppoIntMent();
        public XamScheduleDataManager CurrentXamScheduleDataManager = null;
        public FrameworkElement CurrentContainer = null;
        private const string DynamicFieldLabelC = "DynamicFieldLabel";
        private const string DynamicFieldTextBoxC = "DynamicFieldTextBox";
        private const string ChildAppointmentLabelC = "ChildAppointmentLabel";
        private const string ChildAppointmentAddButtonC = "ChildAppointmentAddButton";
        private const string ChildAppointmentDeleteButtonC = "ChildAppointmentDeleteButton";
        private const string ChildAppointmentEditButtonC = "ChildAppointmentEditButton";
        
        public Customized_Appointment_Dialog()
        {
            InitializeComponent();
        }

        public Customized_Appointment_Dialog(ActivityBase activity, XamScheduleDataManager dataManager, FrameworkElement container)
        {
            InitializeComponent();
            CurrentXamScheduleDataManager = dataManager;
            CurrentContainer = container;
            CurrentDataManager = MainPage.DataManager;
            if (activity is ExtendedAppoIntMent)    //edit existing
                CurrentActivity = (ExtendedAppoIntMent)activity;
            else if (activity is Appointment)   //create new
            {
                CurrentActivity.SetFromAppointment((Appointment)activity);
                if(CurrentActivity.Id != null)
                {
                    ((ObservableCollection<Appointment>)((ListScheduleDataConnector)CurrentXamScheduleDataManager.DataConnector).AppointmentItemsSource).Remove(activity as Appointment);
                    CurrentActivity.Id = null;
                }
                NewCalendarItem = new i_CalendarItem()
                {
                    CalendarItem_ID = NewCalendarItemID,
                    CalendarItem_Calendar_ID = Utils.ReplaceNULL,
                    Verb_ID = 2,
                    Entry_ID = 2053,
                    Entry_Name = "VIP Pre Arrival",
                    Status_ID = 120,
                    StatusNote = "0",
                    Create_Date = DateTime.Now,
                    Update_Date = DateTime.Now,
                    Created_User_ID = 1,
                    Salutation = "Mr.",
                    FirstName = CurrentActivity.Subject,
                    MiddleName = string.Empty,
                    LastName = string.Empty,
                    Start_Date = CurrentActivity.Start,
                    End_Date = CurrentActivity.End,
                    GUID = System.Guid.NewGuid().ToString()
                };

                int MaxCalendarItem_ID = 0;
                foreach (var CurCalendarItem in CurrentDataManager.Data.CalendarItemsC)
                    if (CurCalendarItem.CalendarItem_ID > MaxCalendarItem_ID)
                        MaxCalendarItem_ID = CurCalendarItem.CalendarItem_ID;
                foreach (var CurCalendarItem in CurrentDataManager.Data.CalendarItemsC)
                    if (CurCalendarItem.CalendarItem_ID == NewCalendarItemID)
                        CurCalendarItem.CalendarItem_ID = MaxCalendarItem_ID++;
                        
                CurrentDataManager.Data.CalendarItemsC.Add(NewCalendarItem);
                CurrentActivity.Appointment_Summary = CurrentDataManager.GetOnevw_Appointment_SummaryFromIsolatedStorage(NewCalendarItem.CalendarItem_ID);
                CurrentActivity.UpdateFillColorEx();
                CurrentDataManager.Data.CalendarItemsC.Remove(NewCalendarItem);
            }
            
            CurrentDataManager.GetAppointment_DetailFromODataServerCallbak += new EventHandler<EventArgs>(GetAppointment_DetailFromODataServer_Completed);
            CurrentDataManager.Getvw_Appointment_DetailFromODataServer(CurrentActivity.Appointment_Summary.CalendarItem_ID, -1, NewCalendarItem);
        }//public Customized_Appointment_Dialog(ActivityBase activity, XamScheduleDataManager dataManager, FrameworkElement container)

        private void GetAppointment_DetailFromODataServer_Completed(object sender, EventArgs e)
        {            
            CurrentDataManager.GetAppointment_DetailFromODataServerCallbak -= new EventHandler<EventArgs>(GetAppointment_DetailFromODataServer_Completed);
            if (!(sender is ObservableCollection<i_vw_Appointment_Detail>))
                return;
            Currentvw_Appointment_DetailList = sender as ObservableCollection<i_vw_Appointment_Detail>;
            BindDataToControls();            
        }


        private void BindDataToControls()
        {
            i_vw_Appointment_Detail Currentvw_Appointment_Detail = Currentvw_Appointment_DetailList.First();
            FirstNameTB.Text = Currentvw_Appointment_Detail.FirstName.TrimEnd();
            LastNameTB.Text = Currentvw_Appointment_Detail.LastName.TrimEnd();
            DescriptionTB.Text = Currentvw_Appointment_Detail.Entry;
            StartTimeDP.SelectedDate = Currentvw_Appointment_Detail.Start_Date;
            EndTimeDP.SelectedDate = Currentvw_Appointment_Detail.End_Date;
            bool IsAllDayEvent = Currentvw_Appointment_Detail.Start_Date == Currentvw_Appointment_Detail.End_Date.AddDays(-1);
            AllDayEventTB.IsChecked = IsAllDayEvent;
            SetAllDayEventVisibility();
            if (!IsAllDayEvent)
            {
                DateTime StartDetailTime = Currentvw_Appointment_Detail.Start_Date;
                DateTime EndDetailTime = Currentvw_Appointment_Detail.End_Date;
                StartTimeDetailCB.Items.Add(new ComboBoxItem() { Content = StartDetailTime.Hour.ToString() + ":" +
                                          (StartDetailTime.Minute != 0 ? StartDetailTime.Minute.ToString() : "00")     });
                StartTimeDetailCB.SelectedIndex = StartTimeDetailCB.Items.Count - 1;
                EndTimeDetailCB.Items.Add(new ComboBoxItem() { Content = EndDetailTime.Hour.ToString() + ":" +
                                            (EndDetailTime.Minute != 0 ? EndDetailTime.Minute.ToString() : "00")    });
                EndTimeDetailCB.SelectedIndex = EndTimeDetailCB.Items.Count - 1;
            }

            var CurrentCalendatItem =  NewCalendarItem != null ? 
                                            NewCalendarItem : 
                                            CurrentDataManager.FindCalendarItemViaID(CurrentActivity.Appointment_Summary.CalendarItem_ID);
            VerbCB.Items.Clear();
            foreach (var CurrentVerb in CurrentDataManager.Data.VerbC)
            {
                VerbCB.Items.Add(new ExtendedComboBoxItem() 
                        {
                               ExtendedData = CurrentVerb.Verb_ID,
                               Content = new TextBlock() { Text = CurrentVerb.Verb_Name } ,
                               ExtendedDataString = CurrentVerb.Verb_Name
                        });
                if (Currentvw_Appointment_Detail.Verb_ID == CurrentVerb.Verb_ID)
                    VerbCB.SelectedIndex = VerbCB.Items.Count - 1;

            }

            EntryCB.Items.Clear();
            foreach (var CurrentEntry in CurrentDataManager.Data.EntryC)
            {
                EntryCB.Items.Add(new ExtendedComboBoxItem()
                    {
                        ExtendedData = CurrentEntry.Entry_ID,
                        Content = new TextBlock() { Text = CurrentEntry.Entry_Name },
                        ExtendedDataString = CurrentEntry.Entry_Name
                    });
                if (Currentvw_Appointment_Detail.Entry_ID == CurrentEntry.Entry_ID)            
                    EntryCB.SelectedIndex = EntryCB.Items.Count - 1;            
                
            }
            
            if (CurrentActivity.Appointment_Summary != null)
                DynamicCreateChildAppointments(CurrentActivity.Appointment_Summary.CalendarItem_ID);
        }//private void BindDataToControls()
        
        private void DynamicCreateFields()
        {   
            int FieldHeight = 25;
            int SpaceBetweenFields = 4;
            int FieldCount = 1;
            int CurrentFieldY = 0;
            SaveDynamicFieldValues();
            DynamicFieldsCanvas.Children.Clear();
            foreach (var Currentvw_Appointment_Detail in Currentvw_Appointment_DetailList)
            {                
                DynamicFieldsCanvas.Children.Add(new Label()
                   {
                        Name = DynamicFieldLabelC + FieldCount.ToString(),
                        Height = FieldHeight,
                        Width = 140,
                        Content = Currentvw_Appointment_Detail.Field,
                        Margin = new Thickness(2, CurrentFieldY, 0, 0),
                        HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right
                    });
                
                ExtendedTextBox DynamicFieldsTextBox = new ExtendedTextBox()
                    {
                        Name = DynamicFieldTextBoxC + FieldCount.ToString(),
                        Height = FieldHeight,
                        Width = 210,
                        Text = Currentvw_Appointment_Detail.Value,
                        ExtendedData = Currentvw_Appointment_Detail.Field_ID,
                        ExtendedData2 = Currentvw_Appointment_Detail.CalendarItem_ID,
                        ExtendedData3 = Currentvw_Appointment_Detail.Value.Length > 0 ? 1 : 0,
                        Margin = new Thickness(150, CurrentFieldY, 0, 0)
                    };
                
                ComboBox DynamicFieldsComboBox = new ComboBox()
                {
                    Name = "DynamicFieldComboBox" + (FieldCount++).ToString(),
                    Height = FieldHeight,
                    Width = 100,                                        
                    Margin = new Thickness(280, CurrentFieldY, 0, 0)                    
                };
                foreach (var CurrentFieldDetails in CurrentDataManager.Data.Field_DetailsC)
                    if (CurrentFieldDetails.Field_ID == Currentvw_Appointment_Detail.Field_ID)
                        DynamicFieldsComboBox.Items.Add(new ExtendedComboBoxItem()
                        {
                            ExtendedData = DynamicFieldsTextBox,
                            Content = new TextBlock() { Text = CurrentFieldDetails.Value }
                        });
                DynamicFieldsComboBox.SelectionChanged += new SelectionChangedEventHandler(FieldDetailsCB_SelectionChanged);
                if(DynamicFieldsComboBox.Items.Count > 0)
                   DynamicFieldsCanvas.Children.Add(DynamicFieldsComboBox);
                DynamicFieldsCanvas.Children.Add(DynamicFieldsTextBox);
                 CurrentFieldY += FieldHeight + SpaceBetweenFields;
            }//foreach (var CurrenField in CurrentDynamicFieldsC)
            DynamicFieldsCanvas.Height = CurrentFieldY + 10;
        }//private void DynamicCreateFields(DataManipulations DataManager)

        private void DynamicCreateChildAppointments(int CurrentCalendarItem_ID)
        {
            if (CurrentActivity.Id == null) //if new
                return;
            ChildAppointmentsCanvas.Children.Clear();

            int AppointmentHeight = 25;
            int SpaceBetweenAppointments = 4;
            int AppointmentCount = 1;
            int CurrentAppointmentY = 0;
            
            
            
            foreach (var CurrentCalendarItem_Related in CurrentDataManager.Data.CalendarItem_RelatedC)
                if (CurrentCalendarItem_Related.CalendarItem_ID == CurrentCalendarItem_ID)
                {
                    var CurrentCalendatItem = CurrentDataManager.FindCalendarItemViaID(CurrentCalendarItem_Related.index);
                    if (CurrentCalendatItem == null)
                        return;
                    ChildAppointmentsCanvas.Children.Add(new Label()
                    {
                        Name = ChildAppointmentLabelC + AppointmentCount.ToString(),
                        Height = AppointmentHeight,
                        Width = 180,
                        Content = CurrentCalendatItem.Salutation + " " + CurrentCalendatItem.FirstName.TrimEnd() + " " + CurrentCalendatItem.MiddleName.TrimEnd() + " " + CurrentCalendatItem.LastName.TrimEnd(),
                        Margin = new Thickness(2, CurrentAppointmentY, 0, 0),
                        HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right
                        
                    });
                    ExtendedButton EditButton = new ExtendedButton()
                    {
                        Name = ChildAppointmentEditButtonC + AppointmentCount.ToString(),
                        Height = AppointmentHeight,
                        Width = 30,
                        Content = "Edit",
                        Margin = new Thickness(190, CurrentAppointmentY, 0, 0),
                        ExtendedData = CurrentCalendatItem.CalendarItem_ID
                    };
                    EditButton.Click += new RoutedEventHandler(EditChildButton_Click);
                    ChildAppointmentsCanvas.Children.Add(EditButton);
                    /*ExtendedButton AddButton = new ExtendedButton()
                    {
                        Name = ChildAppointmentAddButtonC + AppointmentCount.ToString(),
                        Height = AppointmentHeight,
                        Width = 30,
                        Content = "Add",
                        Margin = new Thickness(220, CurrentAppointmentY, 0, 0),
                        ExtendedData = CurrentCalendatItem.CalendarItem_ID
                    };
                    AddButton.Click += new RoutedEventHandler(AddChildButton_Click);
                    ChildAppointmentsCanvas.Children.Add(AddButton);*/
                    ExtendedButton DeleteButton = new ExtendedButton()
                    {
                        Name = ChildAppointmentDeleteButtonC + AppointmentCount.ToString(),
                        Height = AppointmentHeight,
                        Width = 50,
                        Content = "Delete",
                        Margin = new Thickness(230, CurrentAppointmentY, 0, 0),
                        ExtendedData = CurrentCalendatItem.CalendarItem_ID
                    };
                    DeleteButton.Click += new RoutedEventHandler(DeleteChildButton_Click);
                    ChildAppointmentsCanvas.Children.Add(DeleteButton);
                    CurrentAppointmentY += AppointmentHeight + SpaceBetweenAppointments;
                    AppointmentCount++;
                }//foreach (var CurrentCalendarItem_Related in CurrentDataManager.Data.CalendarItem_RelatedC)

            ChildAppointmentsCanvas.Height = CurrentAppointmentY + 10;
        }//private void DynamicCreateChildAppointments(DataManipulations DataManager, int SelectedEntry_ID)

        private void SaveDynamicFieldValues()
        {
            if (DynamicFieldsCanvas.Children.Count == 0)
                return;
            CurrentDataManager.TempAdd_and_UpdateCalendarItem_Field.Clear();
            int MaxCalendarItem_Field_ID = 0;            
            foreach (var CurCalendarItem_Field in CurrentDataManager.Data.CalendarItem_FieldC)
                 if (CurCalendarItem_Field.CalendarItem_Field_ID > MaxCalendarItem_Field_ID)
                     MaxCalendarItem_Field_ID = CurCalendarItem_Field.CalendarItem_Field_ID;

            foreach (var CurrentDynamicControl in DynamicFieldsCanvas.Children)
                if (CurrentDynamicControl is ExtendedTextBox)
                    if ((CurrentDynamicControl as ExtendedTextBox).Text.Length > 0 ||
                        (((int)(CurrentDynamicControl as ExtendedTextBox).ExtendedData3) == 1)) 
                    {
                        ExtendedTextBox CurrentTextBox = CurrentDynamicControl as ExtendedTextBox;             
                        if (CurrentTextBox.ExtendedData is int && CurrentTextBox.ExtendedData2 is int)
                        {  
                            int TempField_ID = (int)CurrentTextBox.ExtendedData;
                            int TempCalendarItem_ID = (int)CurrentTextBox.ExtendedData2;
                            i_CalendarItem_Field TempCalendarItem_Field = null;
                            bool AlreadyExist = false;
                            foreach(var CurCalendarItem_Field in CurrentDataManager.Data.CalendarItem_FieldC)
                                if (CurCalendarItem_Field.CalendarItem_ID == TempCalendarItem_ID && CurCalendarItem_Field.Field_ID == TempField_ID)
                                {
                                    CurCalendarItem_Field.Value = CurrentTextBox.Text;
                                    TempCalendarItem_Field = CurCalendarItem_Field;
                                    AlreadyExist = true;
                                    break;
                                }
                            if (!AlreadyExist)
                            {
                                TempCalendarItem_Field = new i_CalendarItem_Field()
                                {
                                    CalendarItem_Field_ID = ++MaxCalendarItem_Field_ID,
                                    CalendarItem_ID = TempCalendarItem_ID,
                                    Field_ID = (int)CurrentTextBox.ExtendedData,
                                    Value = CurrentTextBox.Text,
                                    Sort = Utils.ReplaceNULL,
                                    GUID = System.Guid.NewGuid().ToString(),
                                    Field_Details_ID = Utils.ReplaceNULL
                                };
                                CurrentDataManager.Data.CalendarItem_FieldC.Add(TempCalendarItem_Field);
                            }
                            CurrentDataManager.TempAdd_and_UpdateCalendarItem_Field.Add(TempCalendarItem_Field);
                        }//else if (CurrentTextBox.ExtendedData is int)
                    }//if ((CurrentDynamicControl as ExtendedTextBox).Text.Length > 0) //skip empty dynamic fields            
        }//private void SaveDynamicFieldValues()

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            SaveDynamicFieldValues();
            DateTime StartTime = StartTimeDP.SelectedDate.HasValue ? StartTimeDP.SelectedDate.Value : DateTime.Now;
            DateTime EndTime = EndTimeDP.SelectedDate.HasValue ? EndTimeDP.SelectedDate.Value : DateTime.Now;
            if (!AllDayEventTB.IsChecked.Value)
            {
                DateTime StartDetailTime = Convert.ToDateTime(((ComboBoxItem)StartTimeDetailCB.SelectedValue).Content);
                DateTime EndDetailTime = Convert.ToDateTime(((ComboBoxItem)EndTimeDetailCB.SelectedValue).Content);
                StartTime = StartTime.AddHours(StartDetailTime.Hour - StartTime.Hour);
                StartTime = StartTime.AddMinutes(StartDetailTime.Minute - StartTime.Minute);
                EndTime = EndTime.AddHours(EndDetailTime.Hour - EndTime.Hour);
                EndTime = EndTime.AddMinutes(EndDetailTime.Minute - EndTime.Minute);
            }

            string CurFirstName = FirstNameTB.Text;
            string CurLastName = LastNameTB.Text;
            int CurVerb_ID = 2;
            int CurEntry_ID = 2053;
            string CurEntry_Name = "VIP Pre Arrival";
            string CurVerb_Name = "Arrange";            
            if (VerbCB.SelectedItem is ExtendedComboBoxItem)
                if (((ExtendedComboBoxItem)VerbCB.SelectedItem).ExtendedData is int)
                {
                    CurVerb_ID = (int)((ExtendedComboBoxItem)VerbCB.SelectedItem).ExtendedData;
                    CurVerb_Name = (string)((ExtendedComboBoxItem)VerbCB.SelectedItem).ExtendedDataString;
                }

            if (EntryCB.SelectedItem is ExtendedComboBoxItem)
                if ((((ExtendedComboBoxItem)EntryCB.SelectedItem).ExtendedData is int) &&
                    (((ExtendedComboBoxItem)EntryCB.SelectedItem).ExtendedDataString is string))
                {
                    CurEntry_ID = (int)((ExtendedComboBoxItem)EntryCB.SelectedItem).ExtendedData;
                    CurEntry_Name = (string)((ExtendedComboBoxItem)EntryCB.SelectedItem).ExtendedDataString;
                }

            bool IsNew = CurrentActivity.Id == null;           
            
            if (IsNew)
             CurrentActivity.Id = ExtendedAppoIntMent.GetNextAppointmentID();
            CurrentActivity.Appointment_Summary.FirstName = CurFirstName;
            CurrentActivity.Appointment_Summary.LastName = CurLastName;
            CurrentActivity.Subject = CurrentActivity.Appointment_Summary.Salutation + " " +
                                                (CurrentActivity.Appointment_Summary.FirstName != null ? CurrentActivity.Appointment_Summary.FirstName.TrimEnd() : string.Empty) +
                                             " " + CurrentActivity.Appointment_Summary.MiddleName.TrimEnd() + " " + CurrentActivity.Appointment_Summary.LastName.TrimEnd();
            CurrentActivity.Location = CurVerb_Name;
            CurrentActivity.Description = DescriptionTB.Text;
            CurrentActivity.Start = StartTime;
            CurrentActivity.End = EndTime;
            
            if (IsNew)
            {
                NewCalendarItem.Verb_ID = CurVerb_ID;
                NewCalendarItem.Entry_ID = CurEntry_ID;
                NewCalendarItem.Entry_Name = CurEntry_Name;
                NewCalendarItem.FirstName = CurFirstName;
                NewCalendarItem.LastName = CurLastName;
                NewCalendarItem.Start_Date = StartTime;
                NewCalendarItem.End_Date = EndTime;
                
                CurrentDataManager.Data.CalendarItemsC.Add(NewCalendarItem);
                CurrentActivity.Appointment_Summary = CurrentDataManager.GetOnevw_Appointment_SummaryFromIsolatedStorage(CurrentActivity.Appointment_Summary.CalendarItem_ID);
                ((ObservableCollection<Appointment>)((ListScheduleDataConnector)CurrentXamScheduleDataManager.DataConnector).AppointmentItemsSource).Add(CurrentActivity);
                CurrentDataManager.SaveOneCalendarIremCallbak += new EventHandler<EventArgs>(SaveOneCalendarIremCallbak_Completed);
                CalendarItem CalendarItemtoServer = i_CalendarItem.ReverseConvert(NewCalendarItem);                
                CurrentDataManager.SaveOneCalendarItemToODataServer(CalendarItemtoServer);

            }//if (IsNew)
            else
            {
                foreach (var CurrentCalendarItem in CurrentDataManager.Data.CalendarItemsC)
                    if (CurrentCalendarItem.CalendarItem_ID == CurrentActivity.Appointment_Summary.CalendarItem_ID)
                    {
                        CurrentCalendarItem.Verb_ID = CurVerb_ID;
                        CurrentCalendarItem.Entry_ID = CurEntry_ID;
                        CurrentCalendarItem.Entry_Name = CurEntry_Name;
                        CurrentCalendarItem.FirstName = CurFirstName;
                        CurrentCalendarItem.LastName = CurLastName;
                        CurrentCalendarItem.Start_Date = StartTime;
                        CurrentCalendarItem.End_Date = EndTime;
                        CurrentCalendarItem.Update_Date = DateTime.Now;
                        CurrentDataManager.Add_and_UpdateCalendarItem_on_Client(CurrentCalendarItem);
                        CurrentDataManager.TempCalendarItemToUpdate = CurrentCalendarItem;
                        CurrentDataManager.SaveOneCalendarIremCallbak += new EventHandler<EventArgs>(UpdateOneCalendarIremCallbak_Completed);
                        CurrentDataManager.UpdateCalendarItem_on_Server();
                        break;
                    }

                

                for (int i = 0; i < CurrentDataManager.Data.vw_Appointment_SummaryC.Count; i++)
                    if (CurrentDataManager.Data.vw_Appointment_SummaryC[i].CalendarItem_ID == CurrentActivity.Appointment_Summary.CalendarItem_ID)
                    {
                        CurrentDataManager.Data.vw_Appointment_SummaryC[i].Copy(CurrentDataManager.GetOnevw_Appointment_SummaryFromIsolatedStorage(CurrentActivity.Appointment_Summary.CalendarItem_ID));
                        CurrentDataManager.Add_and_Updatevw_Appointment_Summary_on_Client(CurrentDataManager.Data.vw_Appointment_SummaryC[i]);
                        CurrentActivity.Appointment_Summary = CurrentDataManager.Data.vw_Appointment_SummaryC[i];
                        break;
                    }                    
                
                CurrentDataManager.SiaqodbFlush();
                ((ObservableCollection<Appointment>)((ListScheduleDataConnector)CurrentXamScheduleDataManager.DataConnector).AppointmentItemsSource).Remove(CurrentActivity);                       ;                                
                ((ObservableCollection<Appointment>)((ListScheduleDataConnector)CurrentXamScheduleDataManager.DataConnector).AppointmentItemsSource).Add(
                    new ExtendedAppoIntMent(CurrentActivity) { Id = ExtendedAppoIntMent.GetNextAppointmentID() });
                
            }//else if (IsNew)
            SpecialClose();
        }//private void OKButton_Click(object sender, RoutedEventArgs e)

        private void UpdateOneCalendarIremCallbak_Completed(object sender, EventArgs e)
        {
            CurrentDataManager.Add_and_UpdateCalendarItem_Field_on_Client();
            CurrentDataManager.SiaqodbFlush();
            CurrentDataManager.Add_and_UpdateCalendarItem_Field_on_Server();
            CurrentDataManager.SaveOneCalendarIremCallbak -= new EventHandler<EventArgs>(UpdateOneCalendarIremCallbak_Completed);
            
        }

        private void SaveOneCalendarIremCallbak_Completed(object sender, EventArgs e)
        {
            if(!(sender is int))
                return;
            int NewCalendarItemIDFromServer = (int)sender;
            foreach (var CurCalendarItem_Field in CurrentDataManager.TempAdd_and_UpdateCalendarItem_Field)
                if (CurCalendarItem_Field.CalendarItem_ID == NewCalendarItemID)
                    CurCalendarItem_Field.CalendarItem_ID = NewCalendarItemIDFromServer;
            CurrentActivity.Appointment_Summary = CurrentDataManager.GetOnevw_Appointment_SummaryFromIsolatedStorage(NewCalendarItemIDFromServer);
            CurrentDataManager.Add_and_Updatevw_Appointment_Summary_on_Client(CurrentActivity.Appointment_Summary);
            CurrentDataManager.Add_and_UpdateCalendarItem_on_Client(NewCalendarItem);
            CurrentDataManager.Add_and_UpdateCalendarItem_Field_on_Client();
            CurrentDataManager.SiaqodbFlush();
            CurrentDataManager.Add_and_UpdateCalendarItem_Field_on_Server();
            CurrentDataManager.SaveOneCalendarIremCallbak -= new EventHandler<EventArgs>(SaveOneCalendarIremCallbak_Completed);
            
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            bool IsNew = CurrentActivity.Id == null;
            if (!IsNew)
            {
                ((ObservableCollection<Appointment>)((ListScheduleDataConnector)CurrentXamScheduleDataManager.DataConnector).AppointmentItemsSource).Remove(CurrentActivity);
                ((ObservableCollection<Appointment>)((ListScheduleDataConnector)CurrentXamScheduleDataManager.DataConnector).AppointmentItemsSource).Add(
                    new ExtendedAppoIntMent(CurrentActivity) { Id = ExtendedAppoIntMent.GetNextAppointmentID() });
            }            
            SpecialClose();
        }//private void CancelButton_Click(object sender, RoutedEventArgs e)
                
        private void RemoveButton_Click(object sender, RoutedEventArgs e)
        {   
            bool IsNew = CurrentActivity.Id == null; 
            if (IsNew)
                SpecialClose();
            else if (MessageBox.Show("Do you really want to delete this appointment ?", "Question", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                ((ObservableCollection<Appointment>)((ListScheduleDataConnector)CurrentXamScheduleDataManager.DataConnector).AppointmentItemsSource).Remove(CurrentActivity);
                SpecialClose();
            }
        }//private void ExportToWordButton_Click(object sender, RoutedEventArgs e)

        private void EditChildButton_Click(object sender, RoutedEventArgs e)
        {
            if (!(sender is ExtendedButton))
                return;
            int CalendarID = (int)(sender as ExtendedButton).ExtendedData;
            foreach (var CurrentChildActivity in ((ObservableCollection<Appointment>)((ListScheduleDataConnector)CurrentXamScheduleDataManager.DataConnector).AppointmentItemsSource))
                if (CurrentChildActivity is ExtendedAppoIntMent)
                    if (CalendarID == (CurrentChildActivity as ExtendedAppoIntMent).Appointment_Summary.CalendarItem_ID)
            {
                CurrentXamScheduleDataManager.DisplayActivityDialog(CurrentChildActivity, (Parent as XamDialogWindow).Parent as Canvas);                
                break;
            }
        }//private void EditChildButton_Click(object sender, RoutedEventArgs e)

        /*private void AddChildButton_Click(object sender, RoutedEventArgs e)
        {
            if (!(sender is ExtendedButton))
                return;            
            ExtendedAppoIntMent NewActivity = new ExtendedAppoIntMent();
            NewActivity.SetFromAppointment((Appointment)CurrentActivity);
            NewActivity.Subject = string.Empty;
            NewActivity.Location = string.Empty;
            NewActivity.Description = string.Empty;
            CurrentDataManager.Data.CalendarItem_RelatedC.Add(new CalendarItem_Related()
                {
                    CalendarItem_ID = CurrentActivity.Appointment_Summary.CalendarItem_ID,
                    //grtetgte
                });
            ((ObservableCollection<Appointment>)((ListScheduleDataConnector)CurrentXamScheduleDataManager.DataConnector).AppointmentItemsSource).Add(NewActivity);
            CurrentXamScheduleDataManager.DisplayActivityDialog(NewActivity, (Parent as XamDialogWindow).Parent as Canvas);
            
                
        }//private void EditChildButton_Click(object sender, RoutedEventArgs e)
        */

        private void DeleteChildButton_Click(object sender, RoutedEventArgs e)
        {
            if (!(sender is ExtendedButton))
                return;
            int CalendarID = (int)(sender as ExtendedButton).ExtendedData;
            if (MessageBox.Show("Do you really want to delete this appointment ?", "Question", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                    foreach (var CurrentCalendarItem_Related in CurrentDataManager.Data.CalendarItem_RelatedC)
                        if (CurrentCalendarItem_Related.CalendarItem_ID == CurrentActivity.Appointment_Summary.CalendarItem_ID &&
                            CurrentCalendarItem_Related.index == CalendarID)
                        {
                            CurrentDataManager.Data.CalendarItem_RelatedC.Remove(CurrentCalendarItem_Related);
                            DynamicCreateChildAppointments(CurrentActivity.Appointment_Summary.CalendarItem_ID);
                            break;
                        }                
            }//if (MessageBox.Show("Do you really want to delete this appointment ?", "Question", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
        }//private void DeleteChildButton_Click(object sender, RoutedEventArgs e)


        private void SpecialClose()
        {
            if (Parent is XamDialogWindow)
                ((XamDialogWindow)Parent).Close();
        }

        private void AllDayEventTB_Click(object sender, RoutedEventArgs e)
        {
            SetAllDayEventVisibility();
        }

        private void SetAllDayEventVisibility()
        {
            bool IsEnabledCBs = !AllDayEventTB.IsChecked.Value;
            StartTimeDetailCB.IsEnabled = IsEnabledCBs;
            EndTimeDetailCB.IsEnabled = IsEnabledCBs;
            if (!IsEnabledCBs && EndTimeDP.SelectedDate.Value.Day <= StartTimeDP.SelectedDate.Value.Day)            
                EndTimeDP.SelectedDate = StartTimeDP.SelectedDate.Value.AddDays(1);            
        }//private void SetAllDayEventVisibility()

        private void EntryCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox)            
                if (((ComboBox)sender).SelectedItem is ExtendedComboBoxItem)
                    if (((ExtendedComboBoxItem)((ComboBox)sender).SelectedItem).ExtendedData is int)                                        
                    {
                        int CurEntryID = (int)((ExtendedComboBoxItem)((ComboBox)sender).SelectedItem).ExtendedData;  
                        if(Currentvw_Appointment_DetailList.Count > 0)
                        {
                            if(Currentvw_Appointment_DetailList.First().Entry_ID != CurEntryID)
                            {
                                CurrentDataManager.GetAppointment_DetailFromODataServerCallbak += new EventHandler<EventArgs>(GetAppointment_DetailFromODataServer_Completed2);                
                                CurrentDataManager.Getvw_Appointment_DetailFromODataServer(Currentvw_Appointment_DetailList.First().CalendarItem_ID, CurEntryID, NewCalendarItem);
                            }
                            else
                               DynamicCreateFields();                
                        }
                    }
        }//private void EntryCB_SelectionChanged(object sender, SelectionChangedEventArgs e)

        private void GetAppointment_DetailFromODataServer_Completed2(object sender, EventArgs e)
        {            
            CurrentDataManager.GetAppointment_DetailFromODataServerCallbak -= new EventHandler<EventArgs>(GetAppointment_DetailFromODataServer_Completed2);
            if (!(sender is ObservableCollection<i_vw_Appointment_Detail>))
                return;
            Currentvw_Appointment_DetailList.Clear();
            Currentvw_Appointment_DetailList = sender as ObservableCollection<i_vw_Appointment_Detail>;
            DynamicCreateFields();                
        }


        private void FieldDetailsCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox)
            {
                ComboBox  CurrentComboBox = (ComboBox)sender;
                if (CurrentComboBox.SelectedItem is ExtendedComboBoxItem)
                {
                    ExtendedComboBoxItem CurrentExtendedComboBoxItem = (ExtendedComboBoxItem)CurrentComboBox.SelectedItem;
                    if (CurrentExtendedComboBoxItem.ExtendedData is ExtendedTextBox)
                    {
                        if (CurrentExtendedComboBoxItem.Content != null)
                        {
                            ((ExtendedTextBox)CurrentExtendedComboBoxItem.ExtendedData).Text = ((TextBlock)CurrentExtendedComboBoxItem.Content).Text;
                            ((ExtendedTextBox)CurrentExtendedComboBoxItem.ExtendedData).Focus();
                        }
                    }
                }//if (CurrentComboBox.SelectedItem is ExtendedComboBoxItem)
            }//if (sender is ComboBox)
        }//private void FieldDetailsCB_SelectionChanged(object sender, SelectionChangedEventArgs e)

        private void ExportToWordButton_Click(object sender, RoutedEventArgs e)
        {
            ExportToWord ExportToWordC = new ExportToWord();
            List<string> ListForExport = new List<string>();
            ListForExport.Add(ExportToWord.FontBoldS);
            ListForExport.Add((string)FirstNameL.Content);
            ListForExport.Add(ExportToWord.FontBoldS);
            ListForExport.Add(FirstNameTB.Text);
            ListForExport.Add(ExportToWord.NewLineS);
            ListForExport.Add(ExportToWord.FontBoldS);
            ListForExport.Add((string)LastNameL.Content);
            ListForExport.Add(ExportToWord.FontBoldS);
            ListForExport.Add(LastNameTB.Text);
            ListForExport.Add(ExportToWord.NewLineS);
            ListForExport.Add(ExportToWord.FontBoldS);
            ListForExport.Add((string)StartTimeL.Content);
            ListForExport.Add(ExportToWord.FontBoldS);
            ListForExport.Add(StartTimeDP.SelectedDate.Value.ToString());
            ListForExport.Add(ExportToWord.NewLineS);
            ListForExport.Add(ExportToWord.FontBoldS);
            ListForExport.Add((string)EndTimeL.Content);
            ListForExport.Add(ExportToWord.FontBoldS);
            ListForExport.Add(EndTimeDP.SelectedDate.Value.ToString());
            ListForExport.Add(ExportToWord.NewLineS);
            ListForExport.Add(ExportToWord.FontBoldS);
            ListForExport.Add("Description:");
            ListForExport.Add(ExportToWord.FontBoldS);
            ListForExport.Add(DescriptionTB.Text);
            ListForExport.Add(ExportToWord.NewLineS);
            if (VerbCB.SelectedItem != null)
            {
                ListForExport.Add(ExportToWord.FontBoldS);
                ListForExport.Add((string)TypeLabel.Content);
                ListForExport.Add(ExportToWord.FontBoldS);
                ListForExport.Add((VerbCB.SelectedItem as ExtendedComboBoxItem).ExtendedDataString);
                ListForExport.Add(ExportToWord.NewLineS);
            }//if (VerbCB.SelectedItem != null)

            if (EntryCB.SelectedItem != null)
            {
                ListForExport.Add(ExportToWord.FontBoldS);
                ListForExport.Add((string)TaskL.Content);
                ListForExport.Add(ExportToWord.FontBoldS);
                ListForExport.Add((EntryCB.SelectedItem as ExtendedComboBoxItem).ExtendedDataString);
                ListForExport.Add(ExportToWord.NewLineS);
            }//if (EntryCB.SelectedItem != null)

            foreach (var CurrentDynamicControl in DynamicFieldsCanvas.Children)
                if (CurrentDynamicControl is ExtendedTextBox)
                    if ((CurrentDynamicControl as ExtendedTextBox).Text.Length > 0) //skip empty dynamic fields
            {
                ExtendedTextBox CurrentTextBox = CurrentDynamicControl as ExtendedTextBox;                
                string CurrentDynamicFieldNumber = CurrentTextBox.Name.Substring(DynamicFieldTextBoxC.Length, CurrentTextBox.Name.Length - DynamicFieldTextBoxC.Length);
                foreach (var CurrentSubDynamicControl in DynamicFieldsCanvas.Children)
                   if (CurrentSubDynamicControl is Label)
                       if (DynamicFieldLabelC + CurrentDynamicFieldNumber ==
                           (CurrentSubDynamicControl as Label).Name)
                       {
                           ListForExport.Add(ExportToWord.FontBoldS);
                           ListForExport.Add("\t" + (CurrentSubDynamicControl as Label).Content as string);
                           ListForExport.Add(ExportToWord.FontBoldS);
                           ListForExport.Add(CurrentTextBox.Text);
                           ListForExport.Add(ExportToWord.NewLineS);
                           break;
                       }
                
            }

            

            if (!ExportToWordC.ExportToWord_SpecialList(ListForExport))
                    MessageBox.Show("This application can't save to word document.\n Please contact you system administrator");
        }//private void ExportToWordButton_Click(object sender, RoutedEventArgs e)

        private void ExportToWordwithTemplateButton_Click(object sender, RoutedEventArgs e)
        {
            ExportToWord ExportToWordC = new ExportToWord();
            Dictionary<string, string> WordsForReplaceInTemplate = new Dictionary<string, string>();
            WordsForReplaceInTemplate["~#%@ Subject~#%@"] = FirstNameTB.Text;
            WordsForReplaceInTemplate["~#%@Location~#%@"] = LastNameTB.Text;
            WordsForReplaceInTemplate["~#%@Start time:~#%@"] = StartTimeDP.SelectedDate.Value.ToString();
            WordsForReplaceInTemplate["~#%@End time:~#%@"] = EndTimeDP.SelectedDate.Value.ToString();
            WordsForReplaceInTemplate["~#%@Description:~#%@"] = DescriptionTB.Text;
            WordsForReplaceInTemplate["~#%@Type:~#%@"] = VerbCB.SelectedItem != null ? (VerbCB.SelectedItem as ExtendedComboBoxItem).ExtendedDataString : String.Empty;
            WordsForReplaceInTemplate["~#%@Task:~#%@"] = EntryCB.SelectedItem != null ? (EntryCB.SelectedItem as ExtendedComboBoxItem).ExtendedDataString : String.Empty;

            if (!ExportToWordC.ExportToWord_withTemplate(WordsForReplaceInTemplate))
                MessageBox.Show("This application can't save to word document.\n Please contact you system administrator");
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            (Parent as XamDialogWindow).BringToFront();         
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            
        }//private void ExportToWordwithTemplateButton_Click(object sender, RoutedEventArgs e)

    }//public partial class Customized_Appointment_Dialog : UserControl
}//namespace Ivvy_Silverlight.Ivvy
